package liquidfs.data.fs;

import java.io.*;

import com.thoughtworks.xstream.annotations.*;
import com.thoughtworks.xstream.converters.*;
import com.thoughtworks.xstream.io.*;

import liquidfs.*;
import liquidfs.core.*;
import liquidfs.data.fs.util.*;

public abstract class LocalLiquidObject extends AbstractLiquidObject implements LiquidObject, Comparable<LiquidObject> {
   
   @XStreamAsAttribute()
   private String path;
   
   @XStreamOmitField()
   private LiquidFileSystem fs;
   
   protected LocalLiquidObject (LiquidFileSystem fs, String path) {
      this.path = path;
      this.fs = fs;
   }
   
   protected LiquidFileSystem getFileSystem() {
      return this.fs;
   }
   
   public String getPath () {
      return this.path;
   }
   
   public String getName () {
      return this.path.substring(this.path.lastIndexOf('/') + 1);
   }
   
   @Override
   public boolean exists() {
      File file = this.getFileSystem().getLocalFile(this.getPath());
      return file.exists();
   }
   
   public abstract LiquidMetadataCache getMetadataCache (); 
   
   public static class LocalLiquidObjectSerializer implements Converter {

      private Application app;
      
      public LocalLiquidObjectSerializer (Application app) {
         this.app = app;
      }
      
      @Override
      @SuppressWarnings("rawtypes")
      public boolean canConvert(Class type) {
         return LocalLiquidObject.class.isAssignableFrom(type);
      }

      @Override
      public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
         LiquidMetadataCache record = ((LocalLiquidObject) source).getMetadataCache();
         context.convertAnother(record);
      }
      
      @Override
      public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
         LiquidMetadataCache cache = (LiquidMetadataCache) context.convertAnother(null, LiquidMetadataCache.class);
         RemoteLiquidObject object = new RemoteLiquidObject(app.getFileSystem(), cache);
       
         return object;
      }
      
   }
}
